package com.security.control.authorize.rbac.service.impl;

import com.security.control.authorize.rbac.service.RbacService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;

import javax.servlet.http.HttpServletRequest;
import java.util.HashSet;
import java.util.Set;

/**
 * @author imoot@gamil.com
 * @date 2019/1/25 0025 14:54
 */
@Component("rbacService")
public class RbacServiceImpl implements RbacService {

    private AntPathMatcher antPathMatcher = new AntPathMatcher();

    @Override
    public boolean hasPermission(HttpServletRequest request, Authentication authentication) {
        Object principal = authentication.getPrincipal();
        boolean hasPermission = false;
        if(principal instanceof UserDetails){
            String username = ((UserDetails)principal).getUsername();
            //读取用户所拥有权限的所有URL
            Set<String> urls = new HashSet<>();//在实际业务场景中需要使用username去数据库查询用户所拥有的url访问列表
            for(String url : urls){
                if(antPathMatcher.match(url,request.getRequestURI())){
                    hasPermission = true;
                    break;
                }
            }
        }
        return hasPermission;
    }
}
